﻿using DLL.Net.MS.Models;
using DLL.NET50.DB.MS.AdviceAndDrug;
using DLL.NET50.DB.MS.AdviceAndDrug.ORM.Service;
using DLL.NET50.DB.MS.ORM.Service;
using DLL.NET50.DB.MS.PIVASAndDicDrug.ORM;
using DLL.NET50.DB.PIVAS.Entitys.DTO;
using DLL.NET60.DB.MS.Entity.DTO;
using DLL.NET70.Infrastructure.EventAggregator;
using DLL.NET70.Infrastructure.Prism.MVVM;

using DLL.NetStandard.FlushRobot.MS.Entity.Param;
using DLL.Standard.Infrastructure.Entity;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Regions;
using Prism.Services.Dialogs;

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;

namespace Module.AutoRun.ViewModels
{
    public class PUC_MS_StandAloneViewModel : CMVVMBase, IRegionMemberLifetime
    {
        #region navigate

        public bool KeepAlive
        {
            get
            {
                return false;//这个的作用是，只要离开当前切面，就注销掉当前页面
                //return true;//这个的作用是，只要离开当前切面，就注销掉当前页面
            }
        }

        #endregion navigate

        #region property

        private ObservableCollection<DTO_adi_work_file> _l_Object = new ObservableCollection<DTO_adi_work_file>();

        public ObservableCollection<DTO_adi_work_file> l_Object
        {
            get { return _l_Object; }
            set
            {
                SetProperty(ref _l_Object, value);
            }
        }

        private DTO_adi_work_file _selectObject = new DTO_adi_work_file();

        public DTO_adi_work_file SelectObject
        {
            get { return _selectObject; }
            set
            {
                SetProperty(ref _selectObject, value);
            }
        }

        private int _selectDrugIndex = -1;

        public int SelectDrugIndex
        {
            get { return _selectDrugIndex; }
            set
            {
                SetProperty(ref _selectDrugIndex, value);
            }
        }

        //选药
        private bool _selectDrugEnable = true;//"False"

        public bool SelectDrugEnable
        {
            get { return _selectDrugEnable; }
            set
            {
                SetProperty(ref _selectDrugEnable, value);
            }
        }

        //结余模式使能标志位
        private int _SurplusModeIndex = 0;

        public int SurplusModeIndxe
        {
            get { return _SurplusModeIndex; }
            set
            {
                SetProperty(ref _SurplusModeIndex, value);
                if (value == 1)
                {
                    RealDoseEnable = true;
                }
                else
                {
                    RealDoseEnable = false;
                }
            }
        }

        private object _cb_SurplusModeSelectItem;

        public object cb_SurplusModeSelectItem
        {
            get { return _cb_SurplusModeSelectItem; }
            set { SetProperty(ref _cb_SurplusModeSelectItem, value); }
        }

        //SurplusEnable
        private bool _SurplusEnable = true;

        public bool SurplusEnable
        {
            get { return _SurplusEnable; }
            set
            {
                SetProperty(ref _SurplusEnable, value);
            }
        }

        private int _oldSelectIndex = -1;

        //修改变量： 西林瓶数量
        private ObservableCollection<int> _sourceModifyDrugCount = new ObservableCollection<int>();

        public ObservableCollection<int> SourceModifyDrugCount
        {
            get { return _sourceModifyDrugCount; }
            set
            {
                SetProperty(ref _sourceModifyDrugCount, value);
            }
        }

        private int _drugCountIndex = -1;

        public int DrugCountIndex
        {
            get { return _drugCountIndex; }
            set
            {
                if (value != -1)
                {
                    BtnModifyEnable = true;
                }
                SetProperty(ref _drugCountIndex, value);
            }
        }

        private float _realDose = 0;

        public float REALDOSE
        {
            get { return _realDose; }
            set
            {
                SetProperty(ref _realDose, value);
            }
        }

        private bool _btnModifyEnable = false;//"False"

        public bool BtnModifyEnable
        {
            get { return _btnModifyEnable; }
            set
            {
                SetProperty(ref _btnModifyEnable, value);
            }
        }

        //AllEnable
        private bool _AllEnable = true;//"False"

        public bool AllEnable
        {
            get { return _AllEnable; }
            set
            {
                SetProperty(ref _AllEnable, value);
            }
        }

        private bool _RealDoseEnable = false;//"False"

        public bool RealDoseEnable
        {
            get { return _RealDoseEnable; }
            set
            {
                SetProperty(ref _RealDoseEnable, value);
            }
        }

        //修改药品数量
        private bool _selectDrugCountEnable = false;//"False"

        public bool SelectDrugCountEnable
        {
            get { return _selectDrugCountEnable; }
            set
            {
                SetProperty(ref _selectDrugCountEnable, value);
            }
        }

        //修改溶媒数量
        private bool _selectSolventCountEnable = false;//"False"

        public bool SelectSolventCountEnable
        {
            get { return _selectSolventCountEnable; }
            set
            {
                SetProperty(ref _selectSolventCountEnable, value);
            }
        }

        //修改变量：溶媒数量
        private ObservableCollection<int> _sourceModifySolventCount = new ObservableCollection<int>() { 0, 1, 2, 3, 4, 5, 6 };

        public ObservableCollection<int> SourceModifySolventCount
        {
            get { return _sourceModifySolventCount; }
            set
            {
                SetProperty(ref _sourceModifySolventCount, value);
            }
        }

        private int _solventCount = -1;

        public int SolventCount
        {
            get { return _solventCount; }
            set
            {
                SetProperty(ref _solventCount, value);
            }
        }

        #endregion property

        private IDialogService _dialogService;
        private IWorkFileService _workFileService;
        private IAdviceAndDicDrugsService _adviceAndDicDrugsService;
        private IPIVASAndDicDrug _piVASAndDicDrug;

        public PUC_MS_StandAloneViewModel(IRegionManager regionManager,
            IEventAggregator eventAggregator,
            IContainerExtension container,
            IWorkFileService workFileService,
            IAdviceAndDicDrugsService adviceAndDicDrugsService,
            IPIVASAndDicDrug pIVASAndDicDrug,
            IDialogService dialogService

            ) : base(regionManager, eventAggregator)
        {
            _eventAggregator = eventAggregator;
            _workFileService = workFileService;
            _dialogService = dialogService;
            _adviceAndDicDrugsService = adviceAndDicDrugsService;
            _piVASAndDicDrug = pIVASAndDicDrug;
            ComboxNameSelectItemChangedCommand = new DelegateCommand(ComboxNameSelectItemChanged);
            SurplusModecbSelectedChangedCommand = new DelegateCommand(SurplusModeComboxSelectedChanged);
            ModdifyCommand = new DelegateCommand(Modify);

            //读取设备文件
            CMS_WR_DeviceConfigParam wr_devcieCofg = new CMS_WR_DeviceConfigParam();
            wr_devcieCofg.ReadParam();
            _deviceConfig = wr_devcieCofg.Param;

            for (int i = 0; i < _deviceConfig.StationColNum; i++)
            {
                advicesForFlush.adviceAndDrugs.Add(new CMS_AdviceAndDrug());
            }

            SourceModifySolventCount.Clear();
            for (int i = 0; i <= _deviceConfig.StationColNum; i++)
            {
                SourceModifySolventCount.Add(i);
            }
            SourceModifyDrugCount.Clear();
            for (int i = 0; i < 13; i++)
            {
                SourceModifyDrugCount.Add(i);
            }
        }

        private CNavigateTopParam _NavigateTopParam = new CNavigateTopParam();

        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            //return PageViews / 3 != 1;
            var obj = navigationContext.Parameters["topParam"] as CNavigateTopParam;
            if (obj != null)
            {
                //if (obj.Length > 0)
                {
                    int v = Convert.ToInt32(obj.AllEnable);
                    if (1 == v)
                    {
                        AllEnable = true;
                    }
                    else
                    {
                        AllEnable = false;
                    }
                }
                _NavigateTopParam = obj;
            }
            base.OnNavigatedTo(navigationContext);
        }

        private CMS_WorkConfigParam _workConfig = new CMS_WorkConfigParam();//加工配置参数
        private CMS_DeviceConfigParam _deviceConfig = new CMS_DeviceConfigParam();//设备硬件参数

        public override void Loaded()
        {
            //读取配药文件
            RegisterCommandMsgReceive();
            List<DTO_adi_work_file> lobj = _workFileService.GetAllWorkFile(0);
            lobj.ForEach(p => l_Object.Add(p)); //遍历list添加到EmployeeList中

            SolventCount = _deviceConfig.StationColNum;
            base.Loaded();
        }

        public override void UnLoaded()
        {
            UnRegisterCommandMsgReceive();
            base.UnLoaded();
        }

        private void ResetAdvices()
        {
            SolventCount = _deviceConfig.StationColNum;
            for (int i = 0; i < SolventCount; i++)
            {
                advicesForFlush.adviceAndDrugs.Add(new CMS_AdviceAndDrug());
            }
        }

        #region datagrid 显示变量

        private int fzzMode = 0;

        //切换药品名称
        public DelegateCommand ComboxNameSelectItemChangedCommand { get; set; }

        private void ComboxNameSelectItemChanged()
        {
            if (SelectObject != null)
            {
                if (SelectDrugIndex != -1)
                {
                    if (SelectObject.Solvent_Name == null)
                    {
                        string str = ("单机文件中，溶媒相关属性没有设置，请到单机文件中进行相关设置！");
                        Application.Current.Dispatcher.Invoke(
                        (Action)delegate ()
                        {
                            _dialogService.ShowDialog("WarningDialog", new DialogParameters($"message={str}"), null);
                        });
                        SelectDrugIndex = -1;
                        return;
                    }

                    if (SelectObject.REALDOSE != (SelectObject.DOSE * SelectObject.DRUG_COUNT))
                    {
                        fzzMode = 1;
                    }
                    else
                    {
                        fzzMode = 0;
                    }
                    if (1 == SurplusModeIndxe)
                    {
                        //结余模式
                        if (SelectObject.REALDOSE >= SelectObject.DRUG_COUNT * SelectObject.DOSE)
                        {
                            string str = ("非整只模式，实际剂量与药品数量不匹配，请重新设置加工文件！");
                            Application.Current.Dispatcher.Invoke(
                            (Action)delegate ()
                            {
                                _dialogService.ShowDialog("WarningDialog", new DialogParameters($"message={str}"), null);
                            });
                            SelectDrugIndex = -1;
                            return;
                        }
                        else
                        {
                            //结余模式，药品数量不可以更改
                            SelectDrugCountEnable = false;
                            SelectSolventCountEnable = true;
                        }
                    }
                    else
                    {
                        //不结余模式，药品数量可以更改
                        SelectDrugCountEnable = true;
                        SelectSolventCountEnable = true;
                    }
                    BtnModifyEnable = true;
                    //不结余模式，药品数量可以更改
                    REALDOSE = SelectObject.REALDOSE;
                    DrugCountIndex = SelectObject.DRUG_COUNT;

                    SelectDrugMessage();
                    _oldSelectIndex = SelectDrugIndex;
                }
                else
                {
                    SelectDrugCountEnable = false;
                    SelectSolventCountEnable = false;
                    BtnModifyEnable = false;
                }
            }
        }

        //修改药品数量和溶媒数量
        public DelegateCommand ModdifyCommand { get; set; }

        private void Modify()
        {
            if (SelectObject != null)
            {
                if ((SelectObject.DRUG_COUNT == 0) && (SolventCount == 0))
                {
                    LogMessage("请更改药品数量或溶媒数量在点击更改按钮！");
                }
                else
                {
                    if (1 == SurplusModeIndxe)
                    {
                        if ((SelectObject.REALDOSE >= SelectObject.DOSE))
                        {
                            string str = ("结余模式，实际剂量与药品数量不匹配，请重新设置实际配药剂量");
                            Application.Current.Dispatcher.Invoke(
                            (Action)delegate ()
                            {
                                _dialogService.ShowDialog("WarningDialog", new DialogParameters($"message={str}"), null);
                                //_dialogService.ShowDialog("SuccessDialog", new DialogParameters($"message={str}"), null);
                            });
                            return;
                        }
                    }
                    AlterDrugMessage();
                }
            }
        }

        public DelegateCommand SurplusModecbSelectedChangedCommand { get; private set; }

        private void SurplusModeComboxSelectedChanged()
        {
            if (cb_SurplusModeSelectItem != null)
            {
                if (SurplusModeIndxe > -1)
                {
                    l_Object.Clear();
                    List<DTO_adi_work_file> lobj = _workFileService.GetAllWorkFile(SurplusModeIndxe);
                    lobj.ForEach(p => l_Object.Add(p)); //遍历list添加到EmployeeList中
                    SelectDrugIndex = -1;
                    SelectDrugCountEnable = false;
                    SelectSolventCountEnable = false;
                    BtnModifyEnable = false;
                }
            }
        }

        //DrugCountSelectedChangedCommand
        public DelegateCommand DrugCountSelectedChangedCommand
        { get { return new DelegateCommand(DrugCountSelectedChanged); } private set { } }

        private void DrugCountSelectedChanged()
        {
            if (SelectObject != null)
            {
                if (DrugCountIndex > 0)
                {
                    if (1 == fzzMode)
                    {
                        float fzzDose = SelectObject.REALDOSE - (DrugCountIndex - 1) * SelectObject.DOSE;
                        REALDOSE = fzzDose + (DrugCountIndex - 1) * SelectObject.DOSE;
                    }
                    else
                    {
                        REALDOSE = (DrugCountIndex) * SelectObject.DOSE;
                    }
                }
            }
        }

        #endregion datagrid 显示变量

        #region 将workFile 转换到医嘱

        private CMS_AdviceAndDrugs advicesForFlush = new CMS_AdviceAndDrugs();

        private void SelectDrugMessage()
        {
            GetAdviceAndDrugs(SelectObject, SolventCount);
            SendAdviceOKMessage(advicesForFlush);
        }

        private void AlterDrugMessage()
        {
            DTO_adi_work_file wf = new DTO_adi_work_file();
            wf = (DTO_adi_work_file)SelectObject.Clone();

            wf.REALDOSE = REALDOSE;
            wf.DRUG_COUNT = DrugCountIndex;
            GetAdviceAndDrugs(wf, SolventCount);
            SendAdviceOKMessage(advicesForFlush);
        }

        private void GetAdviceAndDrugs(DTO_adi_work_file wf, int solventCount)
        {
            for (int i = 0; i < solventCount; i++)
            {
                CMS_AdviceAndDrug advice = new CMS_AdviceAndDrug();
                if (_NavigateTopParam.CanUsedStation[i] == 1)
                {
                    advice = WorkFileToAdvice(wf);
                    advice.Enable = 1;
                    advice.SurPlusMode = SurplusModeIndxe;
                }
                advicesForFlush.adviceAndDrugs[i] = advice;
            }
            for (int i = solventCount; i < _deviceConfig.StationColNum; i++)
            {
                CMS_AdviceAndDrug advice = new CMS_AdviceAndDrug();
                advice.Enable = 0;
                advicesForFlush.adviceAndDrugs[i] = advice;
            }
        }

        private CMS_AdviceAndDrug WorkFileToAdvice(DTO_adi_work_file workFile)
        {
            CMS_AdviceAndDrug advice = new CMS_AdviceAndDrug();
            advice.adviceDrug.Add(new DTO_adi_advice_drug());

            advice.adviceDrug[0].QUANTITY = workFile.DRUG_COUNT;// message.DrugCount;
            advice.adviceDrug[0].DRUG_CODE = workFile.DRUG_CODE;//  message.DrugCode;
            advice.adviceDrug[0].REALDOSE = workFile.REALDOSE;// message.RealDose;
            advice.DrugCountOfOneType.Add(workFile.DRUG_COUNT);
            advice.SurPlusMode = SurplusModeIndxe;
            advice.Drugs.Add(new DTO_adi_dic_drug());
            List<DTO_adi_dic_drug> ldrugs = _adviceAndDicDrugsService.GetDrugByCode(workFile.DRUG_CODE);
            List<DTO_adi_dic_drug> lsolents = _adviceAndDicDrugsService.GetDrugByCode(workFile.Solvent_Code);
            if (ldrugs.Count == 1)
            {
                advice.Drugs[0] = ldrugs[0];
                advice.Solvent = lsolents[0];
                advice.adviceDrug[0].DOSE = advice.Drugs[0].DOSE;
                advice.AdviceHadStop = 0;
                advice.pivasAdvicePatient.BATCH_CODE = "1";
            }
            advice.reValue = 1;
            advice.Enable = 1;
            return advice;
        }

        //发送医嘱获取正常消息
        private void SendAdviceOKMessage(CMS_AdviceAndDrugs adviceAndDrugs)
        {
            CMS_AdvicesMsg msg = new CMS_AdvicesMsg();
            msg.CommandStr = MSDM_CmdStr.AdviceOK;
            msg.adviceAndDrugs = adviceAndDrugs;
            SendAdviceToAutoRun(msg);

            CMS_ShowLabelsMsg msg1 = new CMS_ShowLabelsMsg();
            msg1.CommandStr = MSDM_CmdStr.AdviceOK;
            msg1.adviceAndDrugs = adviceAndDrugs;
            ShowLabelsMsg(msg1);
        }

        //发送消息给配药机主界面
        private void SendAdviceToAutoRun(CMS_AdvicesMsg msg)
        {
            _eventAggregator.GetEvent<CMS_AdvicesMsgEvent>().Publish(msg);
        }

        //发送刷新显示瓶贴消息
        private void ShowLabelsMsg(CMS_ShowLabelsMsg msg)
        {
            msg.ConnectMode = 0;
            _eventAggregator.GetEvent<CMS_ShowLabelsMsgEvent>().Publish(msg);
        }

        #endregion 将workFile 转换到医嘱

        #region 发送消息

        private IEventAggregator _eventAggregator;

        #endregion 发送消息

        #region 接收消息

        public override void CommandMessageReceived(CCommandMessage message)
        {
            if (MSDM_CmdStr.AllEnable == message.CommandStr)
            {
                int val = Convert.ToInt32(message.value);
                if (0 == val)
                {
                    AllEnable = false;
                }
                else
                {
                    AllEnable = true;
                }
            }
            else if (MSDM_CmdStr.AllDisEnable == message.CommandStr)
            {
                AllEnable = false;
            }
            else if (MSDM_CmdStr.SelectDrugEnable == message.CommandStr)
            {
                //选药使能标志位
                int val = Convert.ToInt32(message.value);
                if (0 == val)
                {
                    SelectDrugEnable = false;
                }
                else
                {
                    SelectDrugEnable = true;
                }
            }
            else if (MSDM_CmdStr.SurplusModeSelcetIndex == message.CommandStr)
            {
                //结余模式切换
                int vale = Convert.ToInt32(message.value);
                SurplusModeIndxe = vale;
            }
            else if (MSDM_CmdStr.SurplusModeEnable == message.CommandStr)
            {
                //结余模式使能标志位
                int vale = Convert.ToInt32(message.value);
                if (0 == vale)
                {
                    SurplusEnable = false;
                }
                else
                {
                    SurplusEnable = true;
                }
            }
            else if ((MSDM_CmdStr.SurplusMode == message.CommandStr))
            {
                //结余模式
                int mode = Convert.ToInt32(message.value);
                SurplusModeIndxe = mode;
            }
            else if (MSDM_CmdStr.ResetStart == message.CommandStr)
            {
                //开始复位
                DisableAll();
                SelectDrugIndex = -1;
                _oldSelectIndex = -1;
                SolventCount = _deviceConfig.StationColNum;
            }
            else if ((MSDM_CmdStr.ResetOver == message.CommandStr))
            {
                //复位成功
                AllEnable = true;
                SurplusEnable = true;
                SelectDrugEnable = true;
            }
            else if ((MSDM_CmdStr.Runing == message.CommandStr))
            {
                //设备开始配药
                DisableAll();
            }
            else if ((MSDM_CmdStr.RunOver == message.CommandStr))
            {
                //配药结束
                AllEnable = true;
                BtnModifyEnable = true;
                SelectSolventCountEnable = true;//不允许修改溶媒数量
                if (SurplusModeIndxe == 1)
                {
                    //结余模式，药品的数量不可以修改
                    SelectDrugCountEnable = false;//不允许更改药品数量
                }
                else
                {
                    //不是结余模式，药品的数量可以修改
                    SelectDrugCountEnable = true;//不允许更改药品数量
                }
            }
            else if ((MSDM_CmdStr.ReplaceInjectorOver == message.CommandStr))
            {
                //换针后可以选药
                int val = Convert.ToInt32(message.value);
                if (0 == val)
                {
                    //注射器没有达到使用寿命，换针
                    SendClearLablesMessage();
                    AllEnable = true;
                    SurplusEnable = true;
                    SelectDrugEnable = true;
                    BtnModifyEnable = false;
                    SelectSolventCountEnable = false;
                    SelectDrugCountEnable = false;
                    SelectDrugIndex = -1;
                    _oldSelectIndex = -1;
                }
                else if (1 == val)
                {
                    //注射器达到了使用寿命
                    AllEnable = true;
                }
            }
            base.CommandMessageReceived(message);
        }

        private void DisableAll()
        {
            AllEnable = false;
            SelectDrugEnable = false;//不允许选药
            SurplusEnable = false;//屏蔽 结余模式
            BtnModifyEnable = false;//不允许修改药品数据量
            SelectDrugCountEnable = false;//不允许更改药品数量
            SelectSolventCountEnable = false;//不允许修改溶媒数量
        }

        private void EnableAll()
        {
            AllEnable = true;
            SurplusEnable = true;
            SelectDrugEnable = true;
            SelectDrugCountEnable = true;
            SelectSolventCountEnable = true;
            BtnModifyEnable = true;
        }

        //发送清空瓶贴消息
        public void SendClearLablesMessage()
        {
            CMS_ShowLabelsMsg msg = new CMS_ShowLabelsMsg();
            msg.CommandStr = MSDM_CmdStr.Clear;
            ShowLabelsMsg(msg);
        }

        #endregion 接收消息
    }
}